iT邦幫忙

2023 iThome 鐵人賽

DAY 3
0
自我挑戰組

Leetcode Top Interview 150系列 第 3

605. Can Place Flowers

  • 分享至 

  • xImage
  •  

You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.

Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.

Example 1:

Input: flowerbed = [1,0,0,0,1], n = 1
Output: true
Example 2:

Input: flowerbed = [1,0,0,0,1], n = 2
Output: false

Constraints:

1 <= flowerbed.length <= 2 * 104
flowerbed[i] is 0 or 1.
There are no two adjacent flowers in flowerbed.
0 <= n <= flowerbed.length

# @param {Integer[]} flowerbed
# @param {Integer} n
# @return {Boolean}
def can_place_flowers(flowerbed, n)
    result = true
    idx_lst = []
    flowerbed.each_with_index do |i, idx|                         # 先確認 1 的數量與位置
        idx_lst << idx if i == 1
    end

    count = 0
    flowerbed.each_with_index do |i, idx|
        if i == 1                                                 # 這個位置已經種了
            true
        elsif i == 0
            if flowerbed.length == 1                              # 只有一個空格
                n -= 1
            elsif idx == 0                                        # 位置在頭
                if flowerbed[idx+1] == 0                          # 後面有空格
                    n -= 1
                    flowerbed[idx] = 1
                end
            elsif idx == (flowerbed.length - 1)                   # 位置在末端
                if flowerbed[-2] == 0                             # 前面有空格
                    n -= 1
                    flowerbed[idx] = 1
                end
            else                                                  # 位置在中間
                if flowerbed[idx-1] == 0 && flowerbed[idx+1] == 0 # 兩邊都有空格
                    n -= 1
                    flowerbed[idx] = 1
                end
            end
        end
    end
    result = false if n > 0
    result # 回傳結果
end

上一篇
27. Remove Element
下一篇
2. Add Two Numbers
系列文
Leetcode Top Interview 15015
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言